package helper.com.aop;


import helper.com.utils.ValidatorUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * <p>
 *     控制层方法入参校验切面
 * </p>
 * @author 大忽悠
 * @create 2022/4/13 19:54
 */
@Aspect
@Component
public class MethodParamsValidationAspect {
    @Pointcut("execution(* helper.com.controller.*.*(..))")
    public void point(){}

    /**
     * 对方法进行JSR注解的参数校验，如果校验失败，抛出异常
     */
    @Around("point()")
    public Object vaildJSRAnnoAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        methodParamsValidation(joinPoint);
        return joinPoint.proceed();
    }

    private void methodParamsValidation(ProceedingJoinPoint joinPoint) {
        //方法传入参数
        Object[] args = joinPoint.getArgs();
        //方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //当前对象
        Object thisObj = joinPoint.getThis();
        //进行方法参数的类型校验
        ValidatorUtil.doValid(thisObj,method,args);
    }
}
